package com.front.web.shiro.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.front.web.shiro.mapper.UserMapper;
import com.front.web.shiro.model.User;
import com.front.web.shiro.service.PasswordHelper;
import com.front.web.shiro.service.UserService;
import com.front.web.user.mapper.UserRelationMapper;
import com.front.web.user.model.UserRelation;

@Service
public class UserServiceImpl implements UserService
{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordHelper passwordHelper;
    
    @Autowired
    private UserRelationMapper userRelationMapper;

    public User findByUserName(String userName)
    {
        return userMapper.findByUsername(userName);
    }

    /**
     * 创建用户
     * @param user
     */
    public void createUser(User user)
    {
        // 加密密码
        user.setUserPassword(passwordHelper.encryptPassword(user.getUserPassword()));
        userMapper.createUser(user);
    }

    @Override
    public User findByID(Integer id)
    {
        return userMapper.findById(id);
    }

    @Override
    public void updateUser(User user)
    {
        userMapper.updateByPrimaryKeySelective(user);
    }
    
    /***
     *  更新用户账户余额 
     * @param user
     * @throws Exception
     */
    public void updateUserCoin(User user)throws Exception
    {
    	userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public User selectParentUser(Integer id)
    {
        // 通过当前登陆用户id和is_Parent=0得到直属上级id
        UserRelation userRelation = userRelationMapper.selectParentByUid(id);
        
        // 如果没有找到数据，说明没有直属上级
        if (null == userRelation)
        {
            return null;
        }
        
        // 返回直属上级用户对象
        return userMapper.findById(userRelation.getPid());
    }

    @Override
    public void initUserOnlineStatus()
    {
        userMapper.initUserOnlineStatus();
    }

    public void setUserLine(String userName, Integer lineStatus)
    {
        try
        {
            User user = this.findByUserName(userName.toString());
            
            // 如果状态已经在线或者离线就不更新了
            if (null != user && lineStatus != user.getIsOnline())
            {
                // 设置用户下线
                user.setIsOnline(lineStatus);
                this.updateUser(user);
            }
        }
        catch (Exception e)
        {
            System.err.println(e.getMessage());
        }
    }
}
